<template>
  <!-- 添加或修改盘点计划对话框 -->
  <el-dialog :title="title" v-if="open" v-model="open" width="930px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="130px">
      <el-card class="box-card" shadow="always">
        <template #header>
          <div>
            <span>基本信息</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="供应商名称:" prop="supplierName" style="width: 100%">
              <el-input style="width: 180px" v-model="form.supplierName"></el-input>
              <el-checkbox
                v-model="form.supplierAndCustomer"
                :true-label="1"
                :false-label="0"
                style="margin-left: 10px"
                label="既是供应商又是客户"
              ></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="供应商编号:" prop="supplierCode">
              <el-input v-model="form.supplierCode" style="width: 180px" :disabled="form.id"></el-input>
              <el-checkbox
                @change="isAdd"
                :true-label="1"
                v-model="form.autoItemNo"
                :false-label="0"
                style="margin-left: 10px"
                label="自动递增"
              ></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="供应商分类:" prop="supplierClassifyId">
              <el-select v-model="form.supplierClassifyId" placeholder="请选择供应商分类">
                <el-option v-for="item in baseClassifyList" :key="item.id" :label="item.supplierClassifyName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="采购经理:">
              <el-select v-model="form.operationManager" value-key="" placeholder="" clearable filterable>
                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="预设采购价:">
              <el-select v-model="form.priceType" placeholder="请选择预设采购价">
                <el-option v-for="item in preset_purchase_price" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="来源渠道:">
              <el-select v-model="form.sourceChannel" value-key="" placeholder="请选择来源渠道" clearable filterable>
                <el-option v-for="item in supplier_source" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="供应商标签:">
              <el-select multiple v-model="customerTags" placeholder="请选择供应商标签">
                <el-option v-for="item in supplierTags" :key="item.id" :label="item.tagName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" :offset="0">
            <el-form-item label="地址:" style="width: 100%; display: flex">
              <div style="display: flex; width: 100%">
                <el-cascader :options="options" v-model="selectedOptions" @change="handleChange"> </el-cascader>
                <el-input style="margin-left: 10px" v-model="form.addDetail" placeholder="请输入联系地址"></el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="box-card" shadow="always">
        <template #header>
          <div style="position: relative">
            <span>联系人</span>
            <el-button style="position: absolute; right: 0; bottom: -2px" type="primary" @click="handleConcat(0)">
              <el-icon>
                <Plus />
              </el-icon>
            </el-button>
          </div>
        </template>

        <el-row :gutter="20" v-for="(item, index) in form.supplierContactList" :key="index">
          <el-col :span="12" :offset="0">
            <el-form-item label="姓名:" style="width: 100%" :prop="`supplierContactList.${index}.name`" :rules="rules.name">
              <el-input v-model="item.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="0">
            <el-form-item label="手机:" style="width: 100%" :prop="`supplierContactList.${index}.phone`" :rules="rules.phone">
              <el-input v-model="item.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2" :offset="0">
            <el-button v-show="index > 0" icon="delete" type="text" style="margin-left: 10px" @click="handleConcat(1, index)"> </el-button>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="box-card" shadow="always">
        <template #header>
          <div>
            <span>备注</span>
          </div>
        </template>
        <el-input type="textarea" :rows="3" v-model="form.remark"> </el-input>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import modelMixin from '@/mixins/modelMixin';
import supplier from '@/api/goods/supplier';
import { Plus } from '@element-plus/icons-vue';
import { getUserAllList } from '@/api/system/user';
import { getAutoItemNo } from '@/api/goods/supplier';
import { provinceAndCityData, pcTextArr, regionData, pcaTextArr, codeToText } from 'element-china-area-data';
import { getSupplierTagAllList } from '@/api/goods/supplierTag';
import { getClassifyAllList } from '@/api/goods/classify';
import { useUserStore } from '@/store/modules/user';
import { validateMobile } from '@/utils/validate';
const userStore = useUserStore();
export default {
  name: 'addForm',
  components: {
    Plus
  },
  mixins: [modelMixin],
  props: {
    // classifyList: {
    //   type: Array,
    //   default: () => []
    // },
  },
  data() {
    return {
      funcObj: supplier, //方法对象
      open: false,
      title: '添加供应商',
      form: {
        supplierContactList: [{}]
      },
      options: regionData,
      selectedOptions: [],
      preset_purchase_price: [], //预设采购价
      supplier_source: [], //供应商来源
      userList: [],
      contacts: [{}],
      supplierTags: [],
      customerTags: [],
      rules: {
        supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
        supplierCode: [
          { required: true, message: '请输入供应商编号', trigger: 'change' },
          { validator: this.checkAutoItemNo, trigger: 'change' }
        ],
        supplierClassifyId: [{ required: true, message: '请选择供应商分类', trigger: 'change' }],
        name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
        phone: [{ required: true, validator: validateMobile, trigger: 'blur' }]
      },
      // classifyList: [],
      baseClassifyList: []
    };
  },
  created() {
    this.getClassifyAllList();

    this.getDicts(['preset_purchase_price', 'supplier_source', 'supplier_tags']);
    this.getUserAllList();
    this.getSupplierTagAllList();
  },
  methods: {
    validateMobile,
    add(row) {
      this.open = true;
      this.form = { ...row, operationManager: userStore.$state.userId, autoItemNo: 1, supplierAndCustomer: 0, supplierContactList: [{}] };
      this.title = '添加供应商';
      this.selectedOptions = [];
      this.contacts = [{}];
      this.selectedSaleOptions = [];
      this.customerTags = [];
      this.getClassifyAllList();
      this.isAdd(true);
    },

    /**
     * @编辑
     * @param {*} id
     */
    edit(row) {
      this.title = '编辑供应商';
      this.open = true;
      this.getDetail(row);
      this.getClassifyAllList();
    },

    /** 转换数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.classifyName,
        children: node.children
      };
    },

    handleChange(value) {
      console.log(value);
    },
    getClassifyAllList(callback) {
      let params = { classifyType: 0 };
      getClassifyAllList(params).then((res) => {
        if (res) {
          this.baseClassifyList = res;
          callback && callback(res);
        } else {
          this.$modal.msgError(res);
        }
      });
    },
    handleConcat(type, index) {
      if (type == 0) {
        this.form.supplierContactList.push({});
      } else {
        this.form.supplierContactList.splice(index, 1);
      }
    },
    classifyForm() {
      this.form.country = this.selectedOptions.join(',');
      this.form.customerTag = this.customerTags.join(',');
      this.form.type = 0;
    },
    detailAfter() {
      this.form.supplierContactList = this.form.supplierContactList.length ? this.form.supplierContactList : [{}];
      this.selectedOptions = this.form.country.split(',');
      this.form.supplierAndCustomer = +this.form.supplierAndCustomer;
      this.customerTags = (this.form.customerTag && this.form.customerTag.split(',')) || [];
    },
    // 获取后台用户
    getUserAllList() {
      getUserAllList()
        .then((res) => {
          this.userList = res;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getSupplierTagAllList() {
      getSupplierTagAllList({ tagType: 0 }).then((res) => {
        this.supplierTags = res;
      });
    },
    isAdd(val) {
      if (val) {
        getAutoItemNo().then((res) => {
          this.form.supplierCode = res.data;
          console.log('object :>> ', this.$refs);
          // this.$refs.form.validateField(['supplierCode'])
        });
      } else {
        this.form.supplierCode = '';
      }
    },

    checkAutoItemNo(rule, value, callback) {
      let params = {
        supplierCode: this.form.supplierCode,
        id: this.form.id
      };
      supplier.checkAutoItemNo(params).then((res) => {
        let flag = res.data;
        if (flag) {
          callback(new Error('编号已存在'));
        } else {
          callback();
        }
      });
    }
  }
};
</script>
<style type="text/css" scoped>
.box-card {
  margin-top: 20px;
}
</style>
<style lang="scss">
.el-form-item__content {
  width: auto !important;
}
</style>